Ext.define('AM.view.grid.List' ,{
    extend: 'Ext.grid.Panel',
    alias: 'widget.userlist',
    id: 'userlist',
    store: 'StoreGrid',
    title: 'General',
    requires: [
               'Ext.toolbar.TextItem',
               'Ext.form.field.Checkbox',
               'Ext.form.field.Text',
           ],
    searchValue: null,
    indexes: [],
    currentIndex: null,
    searchRegExp: null,
    caseSensitive: false,
    regExpMode: false,
    matchCls: 'x-livesearch-match',
    defaultStatusText: 'Nothing Found',
    
    initComponent: function() {
    	this.lbar= [
       {
            xtype: "button",
            tooltip: 'Adaugă o înregistrare',
            //text: "Add",
            action: 'add',
//            scale: 'medium',
            iconCls: "btn-add",
            icon: 'images/add.png',
        },'-', {
            xtype: "button",
            tooltip: 'Şterge o înregistrare',
            //text: "Delete",
            disabled: true,
            itemId: 'delete',
//            scale: 'medium',
            //action: 'delete',
            iconCls: "btn-delete",
            icon: 'images/delete.png',
            handler: this.deleteClick,
            scope: this
        }],//'-',
        this.tbar = ['Search',{
                 xtype: 'textfield',
                 name: 'searchField',
                 hideLabel: true,
                 width: 200,
                 listeners: {
                     change: {
                         fn: this.onTextFieldChange,
                         scope: this,
                         buffer: 100
                     }
                 }
            }, {
                xtype: 'button',
                text: '<',
                tooltip: 'Find Previous Row',
                handler: this.onPreviousClick,
                scope: this
            },{
                xtype: 'button',
                text: '>',
                tooltip: 'Find Next Row',
                handler: this.onNextClick,
                scope: this
            },'->',{
                xtype: 'textfield',
                fieldLabel: '<b>Suma initiala</b>',
                labelWidth: 85,
                emptyText: 'Introduceti suma initiala',
                id: 'sumInit',
                listeners: {
                     blur: {
                         fn: this.addSumInit,
                         scope: this,
                         buffer: 100
                     }
                }
            }];
        this.columns = [
            {xtype: 'rownumberer',flex: 1},
            {header:'Denumire',dataIndex:'denum',flex: 8},
            {header: 'Categorie', dataIndex: 'subpro', flex: 4},
            {header: 'Subcategorie', dataIndex: 'cild', flex: 4},
            {header: 'Data', dataIndex: 'data', flex: 3,renderer: Ext.util.Format.dateRenderer("d.m.Y")},
            {header: 'Suma', dataIndex: 'suma', flex: 3}
        ],
        this.viewConfig = {
            stripeRows: false, 
            getRowClass: function(record) {
            	return 'row-' +record.get('tip'); 
            } 
        },
        
        this.callParent();
        this.getSelectionModel().on('selectionchange', this.onSelectChange, this);
    },
    
    afterRender: function() {
        var me = this;
        me.callParent(arguments);
        me.textField = me.down('textfield[name=searchField]');
        //me.statusBar = me.down('statusbar[name=searchStatusBar]');
    },
    // detects html tag
    tagsRe: /<[^>]*>/gm,
    
    // DEL ASCII code
    tagsProtect: '\x0f',
    
    // detects regexp reserved word
    regExpProtect: /\\|\/|\+|\\|\.|\[|\]|\{|\}|\?|\$|\*|\^|\|/gm,
    
    getSearchValue: function() {
        var me = this,
            value = me.textField.getValue();
            
        if (value === '') {
            return null;
        }
        if (!me.regExpMode) {
            value = value.replace(me.regExpProtect, function(m) {
                return '\\' + m;
            });
        } else {
            try {
                new RegExp(value);
            } catch (error) {
                /*me.statusBar.setStatus({
                    text: error.message,
                    iconCls: 'x-status-error'
                });*/
                return null;
            }
            // this is stupid
            if (value === '^' || value === '$') {
                return null;
            }
        }

        return value;
    },
    addSumInit: function(obj, s, os){
        var suma = Ext.getCmp('sumInit').getValue();
        Ext.Ajax.request({
            url: 'data/tools.php',
            scope: this,
            method: "GET",
            params: {
                storeTip: 'addSumInit',
                acction: 'addSumInit',
                data: Ext.Date.format(new Date(), 'Y-m-d'),
                suma: suma,
                UserID: UserID
                },
            success: function(response){
                Ext.getStore('StoreDetail').load({
                    params: {storeTip: 'detail', acction: 'dey', UserID: UserID}
                });
            }
        });
    },
     onTextFieldChange: function() {
         var me = this,
             count = 0;

         me.view.refresh();
         // reset the statusbar
         /*me.statusBar.setStatus({
             text: me.defaultStatusText,
             iconCls: ''
         });*/

         me.searchValue = me.getSearchValue();
         me.indexes = [];
         me.currentIndex = null;

         if (me.searchValue !== null) {
             me.searchRegExp = new RegExp(me.searchValue, 'g' + (me.caseSensitive ? '' : 'i'));
             me.store.each(function(record, idx) {
                 var td = Ext.fly(me.view.getNode(idx)).down('td'),
                     cell, matches, cellHTML;
                 while(td) {
                     cell = td.down('.x-grid-cell-inner');
                     matches = cell.dom.innerHTML.match(me.tagsRe);
                     cellHTML = cell.dom.innerHTML.replace(me.tagsRe, me.tagsProtect);
                     
                     // populate indexes array, set currentIndex, and replace wrap matched string in a span
                     cellHTML = cellHTML.replace(me.searchRegExp, function(m) {
                        count += 1;
                        if (Ext.Array.indexOf(me.indexes, idx) === -1) {
                            me.indexes.push(idx);
                        }
                        if (me.currentIndex === null) {
                            me.currentIndex = idx;
                        }
                        return '<span style="background-color:yellow">' + m + '</span>';
                     });
                     // restore protected tags
                     Ext.each(matches, function(match) {
                        cellHTML = cellHTML.replace(me.tagsProtect, match); 
                     });
                     cell.dom.innerHTML = cellHTML;
                     td = td.next();
                 }
             }, me);

             if (me.currentIndex !== null) {
                 me.getSelectionModel().select(me.currentIndex);
                 /*me.statusBar.setStatus({
                     text: count + ' matche(s) found.',
                     iconCls: 'x-status-valid'
                 });*/
             }
         }

         if (me.currentIndex === null) {
             me.getSelectionModel().deselectAll();
         }
         me.textField.focus();
     },
      
    onPreviousClick: function() {
        var me = this,
            idx;
        if ((idx = Ext.Array.indexOf(me.indexes, me.currentIndex)) !== -1) {
            me.currentIndex = me.indexes[idx - 1] || me.indexes[me.indexes.length - 1];
            me.getSelectionModel().select(me.currentIndex);
         }
    },
    
    onNextClick: function() {
         var me = this,
             idx;
             
         if ((idx = Ext.Array.indexOf(me.indexes, me.currentIndex)) !== -1) {
            me.currentIndex = me.indexes[idx + 1] || me.indexes[0];
            me.getSelectionModel().select(me.currentIndex);
         }
    },
    onSelectChange: function(selModel, selections){
        this.down('#delete').setDisabled(false);
    },
    
	deleteClick: function () {
		var selection = this.getView().getSelectionModel().getSelection()[0];
		//console.log(selection.data.id);
		if (selection) {
			this.store.remove(selection);
			Ext.getStore('StoreInsert').load({
		  		params: {
		  		    storeTip: 'delRow',
		  			acction: 'delrow',
		  			id: selection.data.id
		  		},
		  		callback : function() {
		  			Ext.getStore('StoreDetail').load({
						params: {storeTip: 'detail', acction: 'dey', UserID: UserID}
					});
		  			Ext.getStore('StoreGrafic').load({
						params: {storeTip: 'graphic', acction: 'grafic',UserID: UserID}
					});
		  		}
		  	 });
		}    
	}
});